﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RabbitMQMonitorService
{
    public static class SmsHelper
    {
        private static readonly string AccessKeyId = ConfigurationManager.AppSettings["AccessKeyId"];
        private static readonly string AccessSecret = ConfigurationManager.AppSettings["AccessSecret"];
        private static readonly string PhoneNumbers = ConfigurationManager.AppSettings["PhoneNumbers"];
        private static readonly string SignName = ConfigurationManager.AppSettings["SignName"];
        private static readonly string TemplateCode = ConfigurationManager.AppSettings["TemplateCode"];
        private static readonly string TemplateParams = ConfigurationManager.AppSettings["TemplateParams"];
        private static int PhoneCount = 1;

        /// <summary>
        /// 批量发送短信
        /// </summary>
        /// <returns></returns>
        public static (bool flag, string msg) SendBatchSms()
        {
            GetPhoneCount();

            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", AccessKeyId, AccessSecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendBatchSms";
            // request.Protocol = ProtocolType.HTTP;
            request.AddQueryParameters("PhoneNumberJson", GetParamsJson(0));
            request.AddQueryParameters("SignNameJson", GetParamsJson(1));
            request.AddQueryParameters("TemplateCode", TemplateCode);
            request.AddQueryParameters("TemplateParamJson", GetParamsJson(2));

            try
            {
                CommonResponse response = client.GetCommonResponse(request);
                Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
                var content = System.Text.Encoding.Default.GetString(response.HttpResponse.Content);
                var responseModel = JsonConvert.DeserializeObject<SmsResponseModel>(content);
                if (responseModel.Code != "OK") return (false, responseModel.Message);
                else return (true, responseModel.Message);
            }
            catch (ServerException e)
            {
                Console.WriteLine(e);
                return (false, e.Message);
            }
            catch (ClientException e)
            {
                Console.WriteLine(e);
                return (false, e.Message);
            }
        }

        /// <summary>
        /// 获取电话号码数量
        /// </summary>
        /// <returns></returns>
        public static int GetPhoneCount()
        {
            PhoneCount = PhoneNumbers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Length;
            return PhoneCount;
        }
        /// <summary>
        /// 批量构造参数
        /// </summary>
        /// <param name="type">0：电话号码 1：签名 2：模板参数</param>
        /// <returns></returns>
        public static string GetParamsJson(int type)
        {

            var paramJson = new StringBuilder();
            switch (type)
            {
                case 0:
                    var phonesArray = PhoneNumbers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    paramJson.Append("[");
                    for (var i = 0; i < PhoneCount; i++)
                    {
                        paramJson.Append("\"" + phonesArray[i] + "\"");
                        if (i < PhoneCount - 1) paramJson.Append(",");
                    }
                    paramJson.Append("]");
                    break;
                case 1:
                    paramJson.Append("[");
                    for (var i = 0; i < PhoneCount; i++)
                    {
                        paramJson.Append("\"" + SignName + "\"");
                        if (i < PhoneCount - 1) paramJson.Append(",");
                    }
                    paramJson.Append("]");
                    break;
                case 2:
                    var keyValArrays = TemplateParams.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    var paramCount = keyValArrays.Length;
                    paramJson.Append("[");
                    for (var i = 0; i < PhoneCount; i++)
                    {
                        paramJson.Append("{");
                        for (var j = 0; j < paramCount; j++)
                        {
                            var keyValArray = keyValArrays[j]?.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                            paramJson.Append("\"" + keyValArray[0] + "\":\"" + keyValArray[1] + "\"");
                            if (j < paramCount - 1) paramJson.Append(",");
                        }
                        paramJson.Append("}");
                        if (i < PhoneCount - 1) paramJson.Append(",");
                    }
                    paramJson.Append("]");
                    break;
                default:
                    break;
            }
            return paramJson.ToString();
        }
    }

    public class SmsResponseModel
    {
        /// <summary>
        /// 返回信息
        /// </summary>
        public string Message { get; set; }
        public string RequestId { get; set; }
        public string BizId { get; set; }
        /// <summary>
        /// 正确返回OK
        /// </summary>
        public string Code { get; set; }
    }
}
